import React, { useState, useEffect, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { DictTypeAPI, DictDataAPI } from "@/api/dictionary";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  X,
  Save,
  Upload,
  Clipboard,
  Trash2,
  MapPin,
  Camera,
  FileImage,
  GripVertical,
  ExternalLink,
  Plus,
  Image as ImageIcon,
} from "lucide-react";
import { UploadFileAPI } from "@/api/uploading";
import { PoleSpecAPI } from "@/api/PoleSpec";
import { TowerAPI } from "@/api/Towers";

import { ConductorSpecAPI } from "@/api/ConductorSpec";
import { useToast } from "@/components/ui/use-toast";

import { DragDropContext, Droppable, Draggable } from "@hello-pangea/dnd";

export default function CrossingPointForm({
  point,
  projects,
  onSubmit,
  onCancel,
  isStandalone = false,
  selectedProject = null,
}) {
  const [localPoint, setLocalPoint] = useState({});
  const [uploading, setUploading] = useState({
    sitePhotos: false,
    topViewImage: false,
    frontViewImage: false,
    nettingCalculationImage: false,
  });
  const navigate = useNavigate();
  const [errors, setErrors] = useState({});
  const [specialMeasuresOptions, setSpecialMeasuresOptions] = useState([]);
  const [isLoadingSpecialOptions, setIsLoadingSpecialOptions] = useState(true);
  const [allConductorSpecs, setAllConductorSpecs] = useState([]);
  const [isLoadingConductorSpecs, setIsLoadingConductorSpecs] = useState(true);
  const { toast } = useToast();

  // 新增杆塔相关状态
  const [poleSpecs, setPoleSpecs] = useState([]);
  const [isLoadingPoleSpecs, setIsLoadingPoleSpecs] = useState(false);
  const [selectedPoleLeft, setSelectedPoleLeft] = useState("");
  const [selectedPoleRight, setSelectedPoleRight] = useState("");

  const [voltageLevels, setVoltageLevels] = useState([]);
  const [voltageCrossGenre, setVoltageCrossGenre] = useState([]);
  const [isLoadingVoltage, setIsLoadingVoltage] = useState(true);
  const [crossGenreLoaded, setCrossGenreLoaded] = useState(false);

  // 加载杆塔数据
  useEffect(() => {
    const loadPoleSpecs = async () => {
      if (!TowerAPI) {
        console.error("PoleSpec 实体未加载");
        return;
      }

      try {
        setIsLoadingPoleSpecs(true);
        
        const response = await TowerAPI.getList({ projectId: localPoint.projectId }); 
        const data = Array.isArray(response.data) ? response.data : [];
        setPoleSpecs(data);

        // 初始化时匹配已有杆塔数据
        if (localPoint.towerLeft?.towerNumber) {
          const matchedPole = data.find(
            (pole) => pole.towerNumber === localPoint.towerLeft.towerNumber
          );
          if (matchedPole) setSelectedPoleLeft(matchedPole.id);
        }

        if (localPoint.towerRight?.towerNumber) {
          const matchedPole = data.find(
            (pole) => pole.towerNumber === localPoint.towerRight.towerNumber
          );
          if (matchedPole) setSelectedPoleRight(matchedPole.id);
        }
      } catch (error) {
        toast({
          variant: "destructive",
          title: "加载失败",
          description: "无法加载杆塔规格数据",
        });
        console.error("加载杆塔规格失败:", error);
      } finally {
        setIsLoadingPoleSpecs(false);
      }
    };

    // 确保localPoint初始化后再加载杆塔数据
    if (Object.keys(localPoint).length > 0) {
      loadPoleSpecs();
    }
  }, [localPoint, toast]);

  useEffect(() => {
    const loadVoltageLevels = async () => {
      try {
        setIsLoadingVoltage(true);
        const typeResponse = await DictTypeAPI.getList();
        if (typeResponse.code !== 200 || !typeResponse?.rows?.length) {
          throw new Error("获取字典类型失败");
        }
        const voltageType = typeResponse.rows.find(
          (item) => item.dictName === "电压等级"
        );
        const crossGenreType = typeResponse.rows.find(
          (item) => item.dictName === "跨越类型"
        );
        if (!voltageType || !voltageType.dictType) {
          throw new Error("未找到电压等级的dictType");
        }
        if (!crossGenreType || !crossGenreType.dictType) {
          throw new Error("未找到跨越类型的dictType");
        }

        const dataResponse = await DictDataAPI.getList({
          dictType: voltageType.dictType,
        });
        const crossGenreTypeData = await DictDataAPI.getList({
          dictType: crossGenreType.dictType,
        });
        if (dataResponse.code !== 200 || !dataResponse?.rows) {
          throw new Error("获取电压等级数据失败");
        }
        if (crossGenreTypeData.code !== 200 || !crossGenreTypeData?.rows) {
          throw new Error("获取跨越类型数据失败");
        }

        const formattedLevels = dataResponse.rows
          .sort((a, b) => (a.dictSort || 0) - (b.dictSort || 0))
          .map((item) => ({
            value: item.dictValue,
            label: item.dictLabel,
          }));

        const formattedCrossGenre = crossGenreTypeData.rows
          .sort((a, b) => (a.dictSort || 0) - (b.dictSort || 0))
          .map((item) => ({
            value: item.dictValue,
            label: item.dictLabel,
          }));

        setVoltageLevels(formattedLevels);
        setVoltageCrossGenre(formattedCrossGenre);
        setCrossGenreLoaded(true);
      } catch (error) {
        console.error("加载电压等级和跨越类型失败:", error);
        setVoltageLevels([]);
        setVoltageCrossGenre([]);
      } finally {
        setIsLoadingVoltage(false);
      }
    };

    loadVoltageLevels();
  }, []);

  useEffect(() => {
    if (!ConductorSpecAPI) {
      console.error("ConductorSpec 实体未加载");
      setAllConductorSpecs([]);
      setIsLoadingConductorSpecs(false);
      return;
    }
    const loadConductorSpecs = async () => {
      try {
        const specs = await ConductorSpecAPI.getList();
        console.log(specs, "specsspecsspecsspecsspecs");

        const data = Array.isArray(specs.data) ? specs.data : [];
        setAllConductorSpecs(data);
      } catch (error) {
        toast({
          variant: "destructive",
          title: "加载失败",
          description: "无法加载导线规格数据，部分功能可能受限",
        });
        console.error("加载导线规格失败:", error);
        setAllConductorSpecs([]);
      } finally {
        setIsLoadingConductorSpecs(false);
      }
    };
    loadConductorSpecs();
  }, [toast]);

  useEffect(() => {
    if (point && crossGenreLoaded && !isLoadingConductorSpecs) {
      const isValidCrossingType = voltageCrossGenre.some(
        (item) => item.value === point.crossingType
      );

      let validConductorType = point.conductorType || "";
      const isConductorValid = allConductorSpecs.some(
        (spec) => spec.model === validConductorType
      );

      if (!isConductorValid) validConductorType = "";

      setLocalPoint({
        ...point,
        crossingType: isValidCrossingType ? point.crossingType : "",
        towerLeft: point.towerLeft || {
          id: "", // 新增
          towerNumber: "",
          type: "",
          height: 0,
          towerLeftDistance: 0,
          spanToNextTower: 0, // 新增
        },
        towerRight: point.towerRight || {
          id: "", // 新增
          towerNumber: "",
          type: "",
          height: 0,
          towerLeftDistance: 0,
          spanToNextTower: 0, // 新增
        },
        specialRequirements: point.specialRequirements || [],
        sitePhotos: point.sitePhotos || [],
        requiresPowerOutage: point.requiresPowerOutage || false,
        requiresLiveWork: point.requiresLiveWork || false,
        requiresRoadClosure: point.requiresRoadClosure || false,
        requiresTrafficControl: point.requiresTrafficControl || false,
        requiresNavigationControl: point.requiresNavigationControl || false,
        crossedPowerLineVoltage: point.crossedPowerLineVoltage || "",
        crossedPowerLineOwner: point.crossedPowerLineOwner || "",
        roadGrade: point.roadGrade || null,
        railwayType: point.railwayType || null,
        waterwayLevel: point.waterwayLevel || null,
        trafficVolume: point.trafficVolume || null,
        topViewImage: point.topViewImage || {},
        frontViewImage: point.frontViewImage || {},
        nettingCalculationImage: point.nettingCalculationImage || {},
        conductorType: validConductorType,
      });
    } else if (!point) {
      setLocalPoint({
        projectId: selectedProject?.id || "",
        name: "",
        code: "",
        crossingType: "",
        crossingObject: "",
        crossedObjectWidth: 0,
        latitude: 0,
        longitude: 0,
        spanLength: 0,
        crossingHeight: 0,
        groundClearance: 0,
        windSpeed: 10.0,
        iceThickness: 0.0,
        crossingAngle: 90,
        crossingPosition: "",
        crossingPath: "",
        protectionRequirements: "",
        difficultyLevel: "medium",
        priority: "medium",
        status: "planning",
        remarks: "",
        requiresPowerOutage: false,
        requiresLiveWork: false,
        requiresRoadClosure: false,
        requiresTrafficControl: false,
        requiresNavigationControl: false,
        specialRequirements: [],
        crossedPowerLineVoltage: "",
        crossedPowerLineOwner: "",
        roadGrade: null,
        railwayType: null,
        waterwayLevel: null,
        trafficVolume: null,
        topViewImage: null,
        frontViewImage: null,
        nettingCalculationImage: null,
        sitePhotos: null,
        conductorType: "",
      });
    }
  }, [
    point,
    selectedProject,
    allConductorSpecs,
    isLoadingConductorSpecs,
    toast,
    voltageCrossGenre,
    crossGenreLoaded,
  ]);

  useEffect(() => {
    if (point && crossGenreLoaded && voltageCrossGenre.length > 0) {
      const isValidCrossingType = voltageCrossGenre.some(
        (item) => item.value === point.crossingType
      );

      setLocalPoint((prev) => ({
        ...prev,
        crossingType: isValidCrossingType
          ? point.crossingType
          : prev.crossingType,
      }));
    }
  }, [point, crossGenreLoaded, voltageCrossGenre]);

  useEffect(() => {
    console.log("localPoint.conductorType:", localPoint.conductorType);
    console.log("allConductorSpecs:", allConductorSpecs);
  }, [localPoint.conductorType, allConductorSpecs]);

  useEffect(() => {
    loadSpecialMeasuresOptions();
  }, []);

  const loadSpecialMeasuresOptions = async () => {
    try {
      setIsLoadingSpecialOptions(true);
      const { SystemConfig } = await import("@/api/entities");
      const configList = await SystemConfig.list();
      const specialMeasuresConfig = configList.find(
        (config) =>
          config.configKey === "specialMeasuresOptions" && config.isActive
      );

      if (specialMeasuresConfig && specialMeasuresConfig.configValue) {
        let parsedOptions = null;
        const configValue = specialMeasuresConfig.configValue;

        if (
          configValue &&
          typeof configValue === "object" &&
          configValue.options &&
          Array.isArray(configValue.options)
        ) {
          parsedOptions = configValue.options;
        } else if (
          configValue &&
          typeof configValue === "object" &&
          configValue.value
        ) {
          if (
            typeof configValue.value === "object" &&
            configValue.value.options &&
            Array.isArray(configValue.value.options)
          ) {
            parsedOptions = configValue.value.options;
          } else if (typeof configValue.value === "string") {
            try {
              const correctedJsonString = configValue.value.replace(
                /‘|’|“|”/g,
                '"'
              );
              const parsedJson = JSON.parse(correctedJsonString);
              if (parsedJson.options && Array.isArray(parsedJson.options)) {
                parsedOptions = parsedJson.options;
              }
            } catch (e) {
              console.error("解析系统配置中的value字符串失败:", e);
            }
          }
        } else if (Array.isArray(configValue)) {
          parsedOptions = configValue;
        }

        if (parsedOptions) {
          const validOptions = parsedOptions.filter(
            (option) => option && (option.key || option.label)
          );
          setSpecialMeasuresOptions(validOptions);
        } else {
          setSpecialMeasuresOptions([]);
        }
      } else {
        setSpecialMeasuresOptions([]);
      }
    } catch (error) {
      console.error("加载专项措施选项失败:", error);
      setSpecialMeasuresOptions([]);
    } finally {
      setIsLoadingSpecialOptions(false);
    }
  };

  const handleFieldChange = (field, value) => {
    setLocalPoint((prev) => ({ ...prev, [field]: value }));
    setErrors((prev) => ({ ...prev, [field]: "" }));
  };

  const handleTowerChange = (side, field, value) => {
    setLocalPoint((prev) => ({
      ...prev,
      [side]: {
        ...(prev[side] || {}),
        [field]: value,
      },
    }));
  };

  const towerTypeLabels = {
    tensionTower: "耐张塔",
    straightLineTower: "直线塔",
    angleTower: "转角塔",
    branchTower: "分支塔",
  };

  // 处理杆塔选择变更
  const handlePoleSelect = (side, poleId) => {
    const selectedPole = poleSpecs.find((pole) => pole.id === poleId);
    if (!selectedPole) return;
    console.log(selectedPole, "selectedPoleselectedPoleselectedPole");
    // 更新对应侧的杆塔信息
    handleTowerChange(side, "towerNumber", selectedPole.towerNumber || "");
    handleTowerChange(side, "type", towerTypeLabels[selectedPole.type]);
    handleTowerChange(side, "height", selectedPole.height || 0);
    // handleTowerChange(side, "distanceToRoad", selectedPole.distanceToRoad || 0);
    handleTowerChange(
      side,
      "groundElevation",
      selectedPole.groundElevation || 0
    );
    handleTowerChange(
      side,
      "spanToNextTower",
      selectedPole.spanToNextTower || 0
    );
    handleTowerChange(side, "id", selectedPole.id || "");
    handleTowerChange(
      side,
      "insulatorStringLength",
      selectedPole.insulatorStringLength || 0
    );

    // 更新选择状态
    if (side === "towerLeft") {
      setSelectedPoleLeft(poleId);
    } else {
      setSelectedPoleRight(poleId);
    }
  };

  const handleMultipleFileUpload = async (files) => {
    if (!files || files.length === 0) return;
    setUploading((prev) => ({ ...prev, sitePhotos: true }));
    try {
      const uploadPromises = Array.from(files).map(async (file) => {
        const res = await UploadFileAPI.upload(file);
        return res.data;
      });
      const newPhotos = await Promise.all(uploadPromises);
      const updatedPhotos = [...(localPoint.sitePhotos || []), ...newPhotos];
      handleFieldChange("sitePhotos", updatedPhotos);
    } catch (error) {
      console.error("批量上传现场照片失败:", error);
      alert("照片上传失败，请重试");
    } finally {
      setUploading((prev) => ({ ...prev, sitePhotos: false }));
    }
  };

  const ImageGalleryManager = () => {
    const [selectedImageId, setSelectedImageId] = useState(null);

    const technicalSlots = useMemo(
      () => [
        {
          id: "tech-top",
          type: "technical",
          label: "俯视图",
          field: "topViewImage",
          url: localPoint.topViewImage?.docUrl || "",
        },
        {
          id: "tech-front",
          type: "technical",
          label: "正视图",
          field: "frontViewImage",
          url: localPoint.frontViewImage?.docUrl || "",
        },
        {
          id: "tech-netting",
          type: "technical",
          label: "封网计算图",
          field: "nettingCalculationImage",
          url: localPoint.nettingCalculationImage?.docUrl || "",
        },
      ],
      [
        localPoint.topViewImage,
        localPoint.frontViewImage,
        localPoint.nettingCalculationImage,
      ]
    );

    const sitePhotos = useMemo(() => {
      const photos = Array.isArray(localPoint.sitePhotos)
        ? localPoint.sitePhotos
        : localPoint.sitePhotos
        ? [localPoint.sitePhotos]
        : [];

      return photos.map((photo, index) => ({
        id: `site-photo-${index}-${
          photo.docId ||
          photo.docUrl.substring(photo.docUrl.lastIndexOf("=") + 1)
        }`,
        url: photo.docUrl,
        type: "site",
        fileName: photo.docName || `现场照片 ${index + 1}`,
        data: photo,
      }));
    }, [localPoint.sitePhotos]);

    const allImages = useMemo(
      () => [...technicalSlots, ...sitePhotos],
      [technicalSlots, sitePhotos]
    );

    useEffect(() => {
      if (!selectedImageId && allImages.length > 0) {
        setSelectedImageId(allImages[0].id);
      } else if (
        selectedImageId &&
        !allImages.find((img) => img.id === selectedImageId)
      ) {
        setSelectedImageId(allImages.length > 0 ? allImages[0].id : null);
      }
    }, [allImages, selectedImageId]);

    const selectedImage = useMemo(
      () => allImages.find((img) => img.id === selectedImageId) || null,
      [allImages, selectedImageId]
    );

    const handlePasteImageForTech = async (field) => {
      try {
        const clipboardItems = await navigator.clipboard.read();
        for (const item of clipboardItems) {
          if (item.types.some((type) => type.startsWith("image/"))) {
            const blob = await item.getType(
              item.types.find((type) => type.startsWith("image/"))
            );
            setUploading((prev) => ({ ...prev, [field]: true }));

            const file = new File([blob], `${field}_${Date.now()}.png`, {
              type: blob.type,
            });
            const res = await UploadFileAPI.upload(file);

            handleFieldChange(field, res.data);
            setUploading((prev) => ({ ...prev, [field]: false }));
            return;
          }
        }
        alert("剪贴板中没有图片。");
      } catch (err) {
        console.error("粘贴图片失败:", err);
        alert("无法从剪贴板读取图片。");
        setUploading((prev) => ({ ...prev, [field]: false }));
      }
    };

    const handleFileUploadForTech = async (field, file) => {
      if (!file) return;
      setUploading((prev) => ({ ...prev, [field]: true }));
      try {
        const res = await UploadFileAPI.upload(file);
        handleFieldChange(field, res.data);
      } catch (error) {
        console.error(`上传${field}图片失败:`, error);
        alert("图片上传失败，请重试");
      } finally {
        setUploading((prev) => ({ ...prev, [field]: false }));
      }
    };

    const onDragEnd = (result) => {
      const { source, destination, draggableId } = result;

      if (!destination) return;

      const sourceImage = sitePhotos.find((p) => p.id === draggableId);
      if (!sourceImage) return;

      if (destination.droppableId.startsWith("tech-slot-")) {
        const targetField = destination.droppableId.replace("tech-slot-", "");
        handleFieldChange(targetField, sourceImage.data);

        const newSitePhotos = localPoint.sitePhotos.filter(
          (photo) => photo.docId !== sourceImage.data.docId
        );
        handleFieldChange("sitePhotos", newSitePhotos);
      } else if (destination.droppableId === "site-photos-strip") {
        const reorderedPhotos = Array.from(localPoint.sitePhotos);
        const [moved] = reorderedPhotos.splice(source.index, 1);
        reorderedPhotos.splice(destination.index, 0, moved);
        handleFieldChange("sitePhotos", reorderedPhotos);
      }
    };

    const handleRemoveImage = (id, type, field) => {
      if (type === "technical") {
        handleFieldChange(field, {});
      } else if (type === "site") {
        const photoToRemove = sitePhotos.find((p) => p.id === id);
        if (photoToRemove && photoToRemove.data?.docId) {
          const updatedPhotos = (localPoint.sitePhotos || []).filter(
            (photo) => photo.docId !== photoToRemove.data.docId
          );
          handleFieldChange("sitePhotos", updatedPhotos);
        }
      }
    };

    return (
      <DragDropContext onDragEnd={onDragEnd}>
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <Label className="text-sm font-medium">
              图纸与照片 ({sitePhotos.length}张现场照片)
            </Label>
            <div className="flex gap-2">
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() =>
                  document.getElementById("multi-photo-upload").click()
                }
                disabled={uploading.sitePhotos}
              >
                <Camera className="w-4 h-4 mr-2" />
                {uploading.sitePhotos ? "上传中..." : "添加现场照片"}
              </Button>
              <input
                type="file"
                id="multi-photo-upload"
                multiple
                accept="image/*"
                className="hidden"
                onChange={(e) => handleMultipleFileUpload(e.target.files)}
              />
            </div>
          </div>

          {allImages.length > 0 && selectedImage && (
            <div className="relative">
              <img
                src={selectedImage?.url}
                alt={selectedImage?.label || `现场照片`}
                className="w-full h-[35rem] object-contain border rounded-lg bg-gray-50"
              />

              {selectedImage && (
                <Button
                  type="button"
                  variant="destructive"
                  size="sm"
                  className="absolute top-2 right-2"
                  onClick={() =>
                    handleRemoveImage(
                      selectedImage.id,
                      selectedImage.type,
                      selectedImage.field
                    )
                  }
                >
                  <Trash2 className="w-4 h-4" />
                </Button>
              )}
              {selectedImage && (
                <div className="absolute bottom-2 left-2 bg-black bg-opacity-50 text-white px-2 py-1 rounded text-sm">
                  {selectedImage.label
                    ? `技术图纸: ${selectedImage.label}`
                    : `现场照片: ${selectedImage.fileName || ""}`}
                </div>
              )}
            </div>
          )}

          <Droppable droppableId="site-photos-strip" direction="horizontal">
            {(provided) => (
              <div
                ref={provided.innerRef}
                {...provided.droppableProps}
                className="flex gap-2 overflow-x-auto pb-2 border-t pt-2"
              >
                {technicalSlots.map((slot) => (
                  <div
                    key={slot.id}
                    className="flex flex-col items-center gap-1"
                  >
                    <Droppable droppableId={`tech-slot-${slot.field}`}>
                      {(provided, snapshot) => (
                        <div
                          ref={provided.innerRef}
                          {...provided.droppableProps}
                          onClick={() => setSelectedImageId(slot.id)}
                          className={`w-24 h-24 border-2 rounded-lg cursor-pointer relative group ${
                            snapshot.isDraggingOver
                              ? "border-blue-500 bg-blue-100"
                              : slot.url
                              ? "border-gray-300"
                              : "border-dashed border-gray-300"
                          } ${
                            selectedImageId === slot.id ? "border-blue-500" : ""
                          }`}
                        >
                          {uploading[slot.field] ? (
                            <div className="w-full h-full flex items-center justify-center">
                              <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"></div>
                            </div>
                          ) : slot.url ? (
                            <img
                              src={slot.url}
                              alt={slot.label}
                              className="w-full h-full object-cover rounded-md"
                            />
                          ) : (
                            <div className="w-full h-full flex flex-col items-center justify-center text-gray-400">
                              <ImageIcon className="w-6 h-6" />
                              <span className="text-xs mt-1 text-center">
                                {slot.label}
                              </span>
                            </div>
                          )}
                          <div className="absolute bottom-0 left-0 right-0 bg-black bg-opacity-60 text-white text-xs p-1 rounded-b-md">
                            {slot.label}
                          </div>
                          {provided.placeholder}
                        </div>
                      )}
                    </Droppable>

                    <div className="flex gap-1">
                      <Button
                        type="button"
                        variant="outline"
                        size="icon"
                        className="w-6 h-6"
                        onClick={() =>
                          document
                            .getElementById(`${slot.field}-upload`)
                            .click()
                        }
                        disabled={uploading[slot.field]}
                        title="选择文件上传"
                      >
                        <Upload className="w-3 h-3" />
                      </Button>
                      <input
                        type="file"
                        id={`${slot.field}-upload`}
                        accept="image/*"
                        className="hidden"
                        onChange={(e) =>
                          handleFileUploadForTech(slot.field, e.target.files[0])
                        }
                      />
                    </div>
                  </div>
                ))}

                {sitePhotos.map((photo, index) => (
                  <Draggable
                    key={photo.id}
                    draggableId={photo.id}
                    index={index}
                  >
                    {(provided, snapshot) => (
                      <div
                        ref={provided.innerRef}
                        {...provided.draggableProps}
                        onClick={() => setSelectedImageId(photo.id)}
                        className={`w-24 h-24 flex-shrink-0 border-2 rounded-lg cursor-pointer relative group ${
                          selectedImageId === photo.id
                            ? "border-blue-500"
                            : "border-gray-300"
                        }`}
                      >
                        <img
                          src={photo.url}
                          alt={`现场照片 ${index + 1}`}
                          className="w-full h-full object-cover rounded-md"
                        />

                        <div
                          {...provided.dragHandleProps}
                          className="absolute top-1 left-1 bg-black bg-opacity-40 p-1 rounded-full text-white opacity-0 group-hover:opacity-100 transition-opacity"
                        >
                          <GripVertical className="w-3 h-3" />
                        </div>
                        <div className="absolute bottom-0 left-0 right-0 bg-black bg-opacity-60 text-white text-xs p-1 rounded-b-md">
                          {photo.fileName || `现场照片 ${index + 1}`}
                        </div>
                      </div>
                    )}
                  </Draggable>
                ))}
                {provided.placeholder}
              </div>
            )}
          </Droppable>

          {allImages.length === 0 && (
            <div className="text-center py-12 border-2 border-dashed border-gray-300 rounded-lg">
              <FileImage className="w-12 h-12 mx-auto mb-2 text-gray-400" />
              <p className="text-gray-500 mb-2">暂无图纸和照片</p>
              <p className="text-sm text-gray-400">
                点击"添加现场照片"或使用上方按钮添加技术图纸
              </p>
            </div>
          )}
        </div>
      </DragDropContext>
    );
  };

  const handleSpecialRequirementToggle = (requirement) => {
    setLocalPoint((prev) => {
      const currentRequirements = new Set(prev.specialRequirements || []);
      if (currentRequirements.has(requirement)) {
        currentRequirements.delete(requirement);
      } else {
        currentRequirements.add(requirement);
      }
      return {
        ...prev,
        specialRequirements: Array.from(currentRequirements),
      };
    });
  };

  const handleBooleanToggle = (field) => {
    setLocalPoint((prev) => ({
      ...prev,
      [field]: !prev[field],
    }));
  };

  const renderSpecialMeasuresOptions = () => {
    const keyMap = {
      requiresPowerOutage: "停电",
      requiresLiveWork: "带电",
      requiresRoadClosure: "封路",
      requiresTrafficControl: "铁路管制",
      requiresNavigationControl: "停航",
    };
    const extraOptions = specialMeasuresOptions.filter(
      (option) => !Object.values(keyMap).includes(option.key)
    );
    return (
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <Label className="text-base font-semibold">特殊情况标记</Label>
          <span className="text-sm text-gray-600">
            勾选此跨越点涉及的特殊情况
          </span>
        </div>
        <div className="p-3 bg-gray-50 rounded-lg space-y-3">
          <Label className="text-sm font-medium text-gray-700">
            主要专项措施
          </Label>
          <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
            <div className="flex items-center space-x-2">
              <Checkbox
                id="reqPowerOutage"
                checked={!!localPoint.requiresPowerOutage}
                onCheckedChange={() =>
                  handleBooleanToggle("requiresPowerOutage")
                }
              />
              <Label
                htmlFor="reqPowerOutage"
                className="text-sm cursor-pointer"
              >
                需停电作业
              </Label>
            </div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="reqLiveWork"
                checked={!!localPoint.requiresLiveWork}
                onCheckedChange={() => handleBooleanToggle("requiresLiveWork")}
              />
              <Label htmlFor="reqLiveWork" className="text-sm cursor-pointer">
                需带电作业
              </Label>
            </div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="reqRoadClosure"
                checked={!!localPoint.requiresRoadClosure}
                onCheckedChange={() =>
                  handleBooleanToggle("requiresRoadClosure")
                }
              />
              <Label
                htmlFor="reqRoadClosure"
                className="text-sm cursor-pointer"
              >
                需封路施工
              </Label>
            </div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="reqTrafficControl"
                checked={!!localPoint.requiresTrafficControl}
                onCheckedChange={() =>
                  handleBooleanToggle("requiresTrafficControl")
                }
              />
              <Label
                htmlFor="reqTrafficControl"
                className="text-sm cursor-pointer"
              >
                需交通/铁路管制
              </Label>
            </div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="reqNavigationControl"
                checked={!!localPoint.requiresNavigationControl}
                onCheckedChange={() =>
                  handleBooleanToggle("requiresNavigationControl")
                }
              />
              <Label
                htmlFor="reqNavigationControl"
                className="text-sm cursor-pointer"
              >
                需停航施工
              </Label>
            </div>
          </div>
        </div>
        {isLoadingSpecialOptions ? (
          <div className="text-center py-3">
            <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600 mx-auto mb-1"></div>
            <span className="text-xs text-gray-500">加载中...</span>
          </div>
        ) : extraOptions.length > 0 ? (
          <div className="p-3 bg-gray-50 rounded-lg space-y-3">
            <Label className="text-sm font-medium text-gray-700">
              其他特殊情况
            </Label>
            <div className="grid grid-cols-2 md:grid-cols-3 gap-2">
              {extraOptions.map((option, index) => {
                const optionKey =
                  option.key || option.label || `dynamicOption_${index}`;
                const optionLabel =
                  option.label || option.key || `其他选项${index + 1}`;
                const isChecked =
                  localPoint.specialRequirements?.includes(optionKey) || false;
                return (
                  <div key={optionKey} className="flex items-center space-x-2">
                    <Checkbox
                      id={`specialDynamic_${optionKey.replace(/\s+/g, "_")}`}
                      checked={isChecked}
                      onCheckedChange={() =>
                        handleSpecialRequirementToggle(optionKey)
                      }
                    />

                    <Label
                      htmlFor={`specialDynamic_${optionKey.replace(
                        /\s+/g,
                        "_"
                      )}`}
                      className="text-sm cursor-pointer leading-tight"
                    >
                      {optionLabel}
                    </Label>
                  </div>
                );
              })}
            </div>
          </div>
        ) : (
          <div className="text-center py-3">{/* 空状态提示 */}</div>
        )}
      </div>
    );
  };

  const validate = () => {
    let newErrors = {};
    if (isStandalone && !localPoint.projectId) {
      newErrors.projectId = "所属项目不能为空";
    }
    if (!localPoint.name) {
      newErrors.name = "跨越点名称不能为空";
    }
    if (!localPoint.crossingType) {
      newErrors.crossingType = "跨越类型不能为空";
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!validate()) {
      alert("请检查表单中的错误。");
      return;
    }
    const ensureTowerData = (tower) => ({
      id: tower?.id || "", // 新增
      spanToNextTower: tower?.spanToNextTower ? parseFloat(tower.spanToNextTower) : null, // 新增
      towerNumber: tower?.towerNumber || "",
      type: tower?.type || "",
      height: tower?.height ? parseFloat(tower.height) : null,
      groundElevation: tower?.groundElevation
        ? parseFloat(tower.groundElevation)
        : null,
      insulatorStringLength: tower?.insulatorStringLength
        ? parseFloat(tower.insulatorStringLength)
        : null,
      distanceToRoad: tower?.distanceToRoad
        ? parseFloat(tower.distanceToRoad)
        : null,
    });
    const dataToSubmit = {
      ...localPoint,
      crossedObjectWidth: localPoint.crossedObjectWidth
        ? parseFloat(localPoint.crossedObjectWidth)
        : null,
      latitude: localPoint.latitude ? parseFloat(localPoint.latitude) : null,
      longitude: localPoint.longitude ? parseFloat(localPoint.longitude) : null,
      spanLength: localPoint.spanLength
        ? parseFloat(localPoint.spanLength)
        : null,
      crossingHeight: localPoint.crossingHeight
        ? parseFloat(localPoint.crossingHeight)
        : null,
      groundClearance: localPoint.groundClearance
        ? parseFloat(localPoint.groundClearance)
        : null,
      windSpeed: localPoint.windSpeed ? parseFloat(localPoint.windSpeed) : null,
      iceThickness: localPoint.iceThickness
        ? parseFloat(localPoint.iceThickness)
        : null,
      crossingAngle: localPoint.crossingAngle
        ? parseFloat(localPoint.crossingAngle)
        : null,
      towerLeft: ensureTowerData(localPoint.towerLeft),
      towerRight: ensureTowerData(localPoint.towerRight),
      crossedPowerLineVoltage: localPoint.crossedPowerLineVoltage || "",
      crossedPowerLineOwner: localPoint.crossedPowerLineOwner || "",
      roadGrade: localPoint.roadGrade || "",
      railwayType: localPoint.railwayType || "",
      waterwayLevel: localPoint.waterwayLevel || "",
      trafficVolume: localPoint.trafficVolume || "",
      requiresPowerOutage: localPoint.requiresPowerOutage || false,
      requiresLiveWork: localPoint.requiresLiveWork || false,
      requiresRoadClosure: localPoint.requiresRoadClosure || false,
      requiresTrafficControl: localPoint.requiresTrafficControl || false,
      requiresNavigationControl: localPoint.requiresNavigationControl || false,
      topViewImage: localPoint.topViewImage || null,
      frontViewImage: localPoint.frontViewImage || null,
      nettingCalculationImage: localPoint.nettingCalculationImage || null,
      sitePhotos: Array.isArray(localPoint.sitePhotos)
        ? localPoint.sitePhotos
        : null,
    };
    onSubmit(dataToSubmit);
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <Card className="w-full max-w-4xl max-h-[90vh] overflow-hidden">
        <CardHeader className="bg-blue-50">
          <CardTitle className="flex items-center justify-between">
            <span className="flex items-center gap-2">
              <MapPin className="w-5 h-5 text-blue-600" />
              {point ? `编辑跨越点: ${localPoint.name || ""}` : "新建跨越点"}
            </span>
            <Button variant="ghost" size="icon" onClick={onCancel}>
              <X className="w-4 h-4" />
            </Button>
          </CardTitle>
        </CardHeader>

        <CardContent className="p-6 overflow-y-auto max-h-[calc(90vh-120px)]">
          <form onSubmit={handleSubmit} className="space-y-6">
            <Tabs defaultValue="basic" className="w-full">
              <TabsList className="grid w-full grid-cols-3">
                <TabsTrigger value="basic">基本信息</TabsTrigger>
                <TabsTrigger value="technical">技术参数</TabsTrigger>
                <TabsTrigger value="gallery">图纸和照片</TabsTrigger>
              </TabsList>

              {/* Basic Info Tab */}
              <TabsContent value="basic" className="space-y-6">
                {isStandalone && (
                  <div>
                    <Label htmlFor="projectId">所属项目 *</Label>
                    <Select
                      value={localPoint.projectId || ""}
                      onValueChange={(value) =>
                        handleFieldChange("projectId", value)
                      }
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="选择项目" />
                      </SelectTrigger>
                      <SelectContent>
                        {projects &&
                          projects
                            .filter(
                              (project) =>
                                project &&
                                project.id &&
                                project.projectName &&
                                project.id.trim() !== "" &&
                                project.projectName.trim() !== ""
                            )
                            .map((project) => (
                              <SelectItem key={project.id} value={project.id}>
                                {project.projectName} (
                                {project.voltageLevel || "未知电压"})
                              </SelectItem>
                            ))}
                      </SelectContent>
                    </Select>
                    {errors.projectId && (
                      <p className="text-sm text-red-600 mt-1">
                        {errors.projectId}
                      </p>
                    )}
                  </div>
                )}

                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                  <div>
                    <Label htmlFor="name">跨越点名称 *</Label>
                    <Input
                      id="name"
                      value={localPoint.name || ""}
                      onChange={(e) =>
                        handleFieldChange("name", e.target.value)
                      }
                      placeholder="输入跨越点名称"
                    />

                    {errors.name && (
                      <p className="text-sm text-red-600 mt-1">{errors.name}</p>
                    )}
                  </div>

                  <div>
                    <Label htmlFor="code">跨越点编号</Label>
                    <Input
                      id="code"
                      value={localPoint.code || ""}
                      onChange={(e) =>
                        handleFieldChange("code", e.target.value)
                      }
                      placeholder="输入编号"
                    />
                  </div>

                  <div>
                    <Label htmlFor="crossingType">跨越类型 *</Label>
                    <Select
                      value={localPoint.crossingType || ""}
                      onValueChange={(value) =>
                        handleFieldChange("crossingType", value)
                      }
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="选择跨越类型" />
                      </SelectTrigger>
                      <SelectContent>
                        {isLoadingVoltage ? (
                          <SelectItem value="null" disabled>
                            加载中...
                          </SelectItem>
                        ) : (
                          voltageCrossGenre.map((level) => (
                            <SelectItem key={level.value} value={level.value}>
                              {level.label}
                            </SelectItem>
                          ))
                        )}
                      </SelectContent>
                    </Select>
                    {errors.crossingType && (
                      <p className="text-sm text-red-600 mt-1">
                        {errors.crossingType}
                      </p>
                    )}
                  </div>

                  <div>
                    <Label htmlFor="crossingObject">跨越对象</Label>
                    <Input
                      id="crossingObject"
                      value={localPoint.crossingObject || ""}
                      onChange={(e) =>
                        handleFieldChange("crossingObject", e.target.value)
                      }
                      placeholder="具体跨越对象名称"
                    />
                  </div>

                  <div>
                    <Label htmlFor="crossedObjectWidth">被跨越物宽度 (m)</Label>
                    <Input
                      id="crossedObjectWidth"
                      type="number"
                      step="0.1"
                      value={localPoint.crossedObjectWidth || ""}
                      onChange={(e) =>
                        handleFieldChange(
                          "crossedObjectWidth",
                          parseFloat(e.target.value) || 0
                        )
                      }
                      placeholder="宽度"
                    />
                  </div>

                  <div>
                    <Label htmlFor="conductorType">导线型号</Label>
                    <div className="flex gap-2">
                      <div className="flex-1">
                        <Select
                          id="conductorType"
                          value={localPoint.conductorType || ""}
                          onValueChange={(value) =>
                            handleFieldChange("conductorType", value)
                          }
                          disabled={isLoadingConductorSpecs}
                        >
                          <SelectTrigger>
                            <SelectValue
                              placeholder={
                                isLoadingConductorSpecs
                                  ? "加载中..."
                                  : "选择导线型号"
                              }
                            />
                          </SelectTrigger>
                          <SelectContent>
                            {allConductorSpecs.map((spec) => (
                              <SelectItem key={spec.id} value={spec.model}>
                                <div className="flex flex-col">
                                  <span className="font-medium">
                                    {spec.model}
                                  </span>
                                </div>
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                      <Button
                        type="button"
                        variant="outline"
                        size="icon"
                        title="新增导线型号"
                        onClick={() => {
                          navigate("/KnowledgeBase#specs", {
                            state: {
                              from: "/current-page-path",
                              isModal: true,
                            },
                          });
                        }}
                      >
                        <Plus className="w-4 h-4" />
                      </Button>
                    </div>
                    <p className="text-xs text-gray-500 mt-1 flex items-center gap-1">
                      <ExternalLink className="w-3 h-3" />
                      点击 + 按钮可跳转到知识库新增导线规格
                    </p>
                    {errors.conductorType && (
                      <p className="text-sm text-red-600 mt-1">
                        {errors.conductorType}
                      </p>
                    )}
                  </div>
                </div>

                <div className="space-y-4">
                  <h3 className="text-lg font-semibold text-gray-800 border-b pb-2">
                    现场勘查信息
                  </h3>

                  {localPoint.crossingType === "powerLineLive" && (
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 p-4 bg-blue-50 rounded-lg">
                      <div>
                        <Label htmlFor="crossedPowerLineVoltage">
                          被跨越电力线路电压等级
                        </Label>
                        <Select
                          value={localPoint.crossedPowerLineVoltage || ""}
                          onValueChange={(value) =>
                            handleFieldChange("crossedPowerLineVoltage", value)
                          }
                        >
                          <SelectTrigger>
                            <SelectValue placeholder="选择电压等级" />
                          </SelectTrigger>
                          <SelectContent>
                            {isLoadingVoltage ? (
                              <SelectItem value="null" disabled>
                                加载中...
                              </SelectItem>
                            ) : (
                              voltageLevels.map((level) => (
                                <SelectItem
                                  key={level.value}
                                  value={level.value}
                                >
                                  {level.label}
                                </SelectItem>
                              ))
                            )}
                          </SelectContent>
                        </Select>
                      </div>

                      <div>
                        <Label htmlFor="crossedPowerLineOwner">
                          被跨越电力线路产权单位
                        </Label>
                        <Input
                          id="crossedPowerLineOwner"
                          value={localPoint.crossedPowerLineOwner || ""}
                          onChange={(e) =>
                            handleFieldChange(
                              "crossedPowerLineOwner",
                              e.target.value
                            )
                          }
                          placeholder="产权单位名称"
                        />
                      </div>
                    </div>
                  )}

                  {(localPoint.crossingType === "highwayExpressway" ||
                    localPoint.crossingType === "highwayGradePlus2") && (
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 p-4 bg-green-50 rounded-lg">
                      <div>
                        <Label htmlFor="roadGrade">公路等级</Label>
                        <Select
                          value={localPoint.roadGrade || ""}
                          onValueChange={(value) =>
                            handleFieldChange("roadGrade", value)
                          }
                        >
                          <SelectTrigger>
                            <SelectValue placeholder="选择公路等级" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="national">国道</SelectItem>
                            <SelectItem value="provincial">省道</SelectItem>
                            <SelectItem value="county">县道</SelectItem>
                            <SelectItem value="township">乡道</SelectItem>
                            <SelectItem value="village">村道</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      <div>
                        <Label htmlFor="trafficVolume">交通流量描述</Label>
                        <Input
                          id="trafficVolume"
                          value={localPoint.trafficVolume || ""}
                          onChange={(e) =>
                            handleFieldChange("trafficVolume", e.target.value)
                          }
                          placeholder="如：日均车流量1000辆"
                        />
                      </div>
                    </div>
                  )}

                  {localPoint.crossingType === "railwayHighSpeed" && (
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 p-4 bg-yellow-50 rounded-lg">
                      <div>
                        <Label htmlFor="railwayType">铁路类型</Label>
                        <Select
                          value={localPoint.railwayType || ""}
                          onValueChange={(value) =>
                            handleFieldChange("railwayType", value)
                          }
                        >
                          <SelectTrigger>
                            <SelectValue placeholder="选择铁路类型" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="highSpeed">高速铁路</SelectItem>
                            <SelectItem value="passenger">客运专线</SelectItem>
                            <SelectItem value="freight">货运铁路</SelectItem>
                            <SelectItem value="urban">城际铁路</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      <div>
                        <Label htmlFor="trafficVolume">列车运行密度</Label>
                        <Input
                          id="trafficVolume"
                          value={localPoint.trafficVolume || ""}
                          onChange={(e) =>
                            handleFieldChange("trafficVolume", e.target.value)
                          }
                          placeholder="如：日均120对列车"
                        />
                      </div>
                    </div>
                  )}

                  {localPoint.crossingType === "riverNavigable" && (
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 p-4 bg-cyan-50 rounded-lg">
                      <div>
                        <Label htmlFor="waterwayLevel">航道等级</Label>
                        <Select
                          value={localPoint.waterwayLevel || ""}
                          onValueChange={(value) =>
                            handleFieldChange("waterwayLevel", value)
                          }
                        >
                          <SelectTrigger>
                            <SelectValue placeholder="选择航道等级" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="I">I级航道</SelectItem>
                            <SelectItem value="II">II级航道</SelectItem>
                            <SelectItem value="III">III级航道</SelectItem>
                            <SelectItem value="IV">IV级航道</SelectItem>
                            <SelectItem value="V">V级航道</SelectItem>
                            <SelectItem value="VI">VI级航道</SelectItem>
                            <SelectItem value="VII">VII级航道</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      <div>
                        <Label htmlFor="trafficVolume">通航情况描述</Label>
                        <Input
                          id="trafficVolume"
                          value={localPoint.trafficVolume || ""}
                          onChange={(e) =>
                            handleFieldChange("trafficVolume", e.target.value)
                          }
                          placeholder="如：日均船舶通行50艘次"
                        />
                      </div>
                    </div>
                  )}
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div>
                    <Label htmlFor="difficultyLevel">施工难度</Label>
                    <Select
                      value={localPoint.difficultyLevel || "medium"}
                      onValueChange={(value) =>
                        handleFieldChange("difficultyLevel", value)
                      }
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="选择难度" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="low">低难度</SelectItem>
                        <SelectItem value="medium">中等难度</SelectItem>
                        <SelectItem value="high">高难度</SelectItem>
                        <SelectItem value="critical">极高难度</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div>
                    <Label htmlFor="priority">优先级</Label>
                    <Select
                      value={localPoint.priority || "medium"}
                      onValueChange={(value) =>
                        handleFieldChange("priority", value)
                      }
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="选择优先级" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="low">低优先级</SelectItem>
                        <SelectItem value="medium">中等优先级</SelectItem>
                        <SelectItem value="high">高优先级</SelectItem>
                        <SelectItem value="urgent">紧急</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                {renderSpecialMeasuresOptions()}
                <div>
                  <Label htmlFor="crossingPointSummary">跨越点情况简述</Label>
                  <Textarea
                    id="crossingPointSummary"
                    value={localPoint.crossingPointSummary || ""}
                    onChange={(e) =>
                      handleFieldChange("crossingPointSummary", e.target.value)
                    }
                    placeholder="其他需要说明的信息..."
                    rows={3}
                  />
                </div>

                <div>
                  <Label htmlFor="remarks">备注信息</Label>
                  <Textarea
                    id="remarks"
                    value={localPoint.remarks || ""}
                    onChange={(e) =>
                      handleFieldChange("remarks", e.target.value)
                    }
                    placeholder="其他需要说明的信息..."
                    rows={3}
                  />
                </div>
              </TabsContent>

              {/* Technical Parameters Tab */}
              <TabsContent value="technical" className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="p-4 bg-blue-50 rounded-lg">
                    <h3
                      className="font-semibold text-blue-900 mb-3"
                      onClick={() => {
                        console.log(poleSpecs, "poleSpecspoleSpecs");
                      }}
                    >
                      左侧杆塔
                    </h3>
                    <div className="space-y-3">
                      <div>
                        <Label htmlFor="towerLeftSelect">选择杆塔</Label>
                        <Select
                          value={selectedPoleLeft || ""}
                          onValueChange={(value) =>
                            handlePoleSelect("towerLeft", value)
                          }
                          disabled={isLoadingPoleSpecs}
                        >
                          <SelectTrigger>
                            <SelectValue
                              placeholder={
                                isLoadingPoleSpecs
                                  ? "加载中..."
                                  : "选择左侧杆塔"
                              }
                            />
                          </SelectTrigger>
                          <SelectContent>
                            {isLoadingPoleSpecs ? (
                              <SelectItem value="null" disabled>
                                加载中...
                              </SelectItem>
                            ) : poleSpecs.length > 0 ? (
                              poleSpecs.map((pole) => (
                                <SelectItem key={pole.id} value={pole.id}>
                                  {pole.towerNumber}
                                </SelectItem>
                              ))
                            ) : (
                              <SelectItem value="null">无杆塔数据</SelectItem>
                            )}
                          </SelectContent>
                        </Select>
                      </div>

                      <div>
                        <Label htmlFor="towerLeftType">杆塔类型</Label>
                        <Input
                          id="towerLeftType"
                          value={localPoint.towerLeft?.type || ""}
                          onChange={(e) =>
                            handleTowerChange(
                              "towerLeft",
                              "type",
                              e.target.value
                            )
                          }
                          placeholder="例如: 直线塔"
                        />
                      </div>

                      <div>
                        <Label htmlFor="towerLeftHeight">杆塔高度 (m)</Label>
                        <Input
                          id="towerLeftHeight"
                          type="number"
                          step="0.1"
                          value={localPoint.towerLeft?.height || ""}
                          onChange={(e) =>
                            handleTowerChange(
                              "towerLeft",
                              "height",
                              parseFloat(e.target.value) || 0
                            )
                          }
                          placeholder="杆塔高度"
                        />
                      </div>

                      <div>
                        <Label htmlFor="towerLeftDistance">
                          距被跨越物距离 (m)
                        </Label>
                        <Input
                          id="towerLeftDistance"
                          type="number"
                          step="0.1"
                          value={localPoint.towerLeft?.distanceToRoad || ""}
                          onChange={(e) =>
                            handleTowerChange(
                              "towerLeft",
                              "distanceToRoad",
                              parseFloat(e.target.value) || 0
                            )
                          }
                          placeholder="距离"
                        />
                      </div>
                      <div>
                        <Label htmlFor="towerLeftNominalHeight">呼称高</Label>
                        <Input
                          id="towerLeftNominalHeight"
                          type="number"
                          step="0.1"
                          value={localPoint.towerLeft?.groundElevation || ""}
                          onChange={(e) =>
                            handleTowerChange(
                              "towerLeft",
                              "groundElevation",
                              parseFloat(e.target.value) || 0
                            )
                          }
                          placeholder="高度"
                        />
                      </div>
                      <div>
                        <Label htmlFor="towerLeftInsulatorStringLength">
                          杆塔绝缘子串长度
                        </Label>
                        <Input
                          id="towerLeftInsulatorStringLength"
                          type="number"
                          step="0.1"
                          value={
                            localPoint.towerLeft?.insulatorStringLength || ""
                          }
                          onChange={(e) =>
                            handleTowerChange(
                              "towerLeft",
                              "insulatorStringLength",
                              parseFloat(e.target.value) || 0
                            )
                          }
                          placeholder="长度"
                        />
                      </div>
                    </div>
                  </div>

                  <div className="p-4 bg-green-50 rounded-lg">
                    <h3 className="font-semibold text-green-900 mb-3">
                      右侧杆塔
                    </h3>
                    <div className="space-y-3">
                      <div>
                        <Label htmlFor="towerRightSelect">选择杆塔</Label>
                        <Select
                          value={selectedPoleRight || ""}
                          onValueChange={(value) =>
                            handlePoleSelect("towerRight", value)
                          }
                          disabled={isLoadingPoleSpecs}
                        >
                          <SelectTrigger>
                            <SelectValue
                              placeholder={
                                isLoadingPoleSpecs
                                  ? "加载中..."
                                  : "选择右侧杆塔"
                              }
                            />
                          </SelectTrigger>
                          <SelectContent>
                            {isLoadingPoleSpecs ? (
                              <SelectItem value="null" disabled>
                                加载中...
                              </SelectItem>
                            ) : poleSpecs.length > 0 ? (
                              poleSpecs.map((pole) => (
                                <SelectItem key={pole.id} value={pole.id}>
                                  {pole.towerNumber}
                                </SelectItem>
                              ))
                            ) : (
                              <SelectItem value="null">无杆塔数据</SelectItem>
                            )}
                          </SelectContent>
                        </Select>
                      </div>

                      <div>
                        <Label htmlFor="towerRightType">杆塔类型</Label>
                        <Input
                          id="towerRightType"
                          value={localPoint?.towerRight?.type || ""}
                          onChange={(e) =>
                            handleTowerChange(
                              "towerRight",
                              "type",
                              e.target.value
                            )
                          }
                          placeholder="例如: 直线塔"
                        />
                      </div>

                      <div>
                        <Label htmlFor="towerRightHeight">杆塔高度 (m)</Label>
                        <Input
                          id="towerRightHeight"
                          type="number"
                          step="0.1"
                          value={localPoint.towerRight?.height || ""}
                          onChange={(e) =>
                            handleTowerChange(
                              "towerRight",
                              "height",
                              parseFloat(e.target.value) || 0
                            )
                          }
                          placeholder="杆塔高度"
                        />
                      </div>

                      <div>
                        <Label htmlFor="towerRightDistance">
                          距被跨越物距离 (m)
                        </Label>
                        <Input
                          id="towerRightDistance"
                          type="number"
                          step="0.1"
                          value={localPoint.towerRight?.distanceToRoad || ""}
                          onChange={(e) =>
                            handleTowerChange(
                              "towerRight",
                              "distanceToRoad",
                              parseFloat(e.target.value) || 0
                            )
                          }
                          placeholder="距离"
                        />
                      </div>
                      <div>
                        <Label htmlFor="towerRightNominalHeight">呼称高</Label>
                        <Input
                          id="towerRightNominalHeight"
                          type="number"
                          step="0.1"
                          value={localPoint.towerRight?.groundElevation || ""}
                          onChange={(e) =>
                            handleTowerChange(
                              "towerRight",
                              "groundElevation",
                              parseFloat(e.target.value) || 0
                            )
                          }
                          placeholder="高度"
                        />
                      </div>
                      <div>
                        <Label htmlFor="towerRightInsulatorStringLength">
                          杆塔绝缘子串长度
                        </Label>
                        <Input
                          id="towerRightInsulatorStringLength"
                          type="number"
                          step="0.1"
                          value={
                            localPoint.towerRight?.insulatorStringLength || ""
                          }
                          onChange={(e) =>
                            handleTowerChange(
                              "towerRight",
                              "insulatorStringLength",
                              parseFloat(e.target.value) || 0
                            )
                          }
                          placeholder="长度"
                        />
                      </div>
                    </div>
                  </div>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                  <div>
                    <Label htmlFor="spanLength">档距 (m)</Label>
                    <Input
                      id="spanLength"
                      type="number"
                      step="0.1"
                      value={localPoint.spanLength || ""}
                      onChange={(e) =>
                        handleFieldChange(
                          "spanLength",
                          parseFloat(e.target.value) || 0
                        )
                      }
                      placeholder="档距"
                    />
                  </div>

                  <div>
                    <Label htmlFor="crossingHeight">跨越高度 (m)</Label>
                    <Input
                      id="crossingHeight"
                      type="number"
                      step="0.1"
                      value={localPoint.crossingHeight || ""}
                      onChange={(e) =>
                        handleFieldChange(
                          "crossingHeight",
                          parseFloat(e.target.value) || 0
                        )
                      }
                      placeholder="跨越高度"
                    />
                  </div>

                  <div>
                    <Label htmlFor="groundClearance">对地距离 (m)</Label>
                    <Input
                      id="groundClearance"
                      type="number"
                      step="0.1"
                      value={localPoint.groundClearance || ""}
                      onChange={(e) =>
                        handleFieldChange(
                          "groundClearance",
                          parseFloat(e.target.value) || 0
                        )
                      }
                      placeholder="对地距离"
                    />
                  </div>

                  <div>
                    <Label htmlFor="windSpeed">设计风速 (m/s)</Label>
                    <Input
                      id="windSpeed"
                      type="number"
                      step="0.1"
                      value={localPoint.windSpeed || ""}
                      onChange={(e) =>
                        handleFieldChange(
                          "windSpeed",
                          parseFloat(e.target.value) || 0
                        )
                      }
                      placeholder="设计风速"
                    />
                  </div>

                  <div>
                    <Label htmlFor="iceThickness">覆冰厚度 (mm)</Label>
                    <Input
                      id="iceThickness"
                      type="number"
                      step="0.1"
                      value={localPoint.iceThickness || ""}
                      onChange={(e) =>
                        handleFieldChange(
                          "iceThickness",
                          parseFloat(e.target.value) || 0
                        )
                      }
                      placeholder="覆冰厚度"
                    />
                  </div>

                  <div>
                    <Label htmlFor="crossingAngle">交叉角度 (°)</Label>
                    <Input
                      id="crossingAngle"
                      type="number"
                      step="0.1"
                      value={localPoint.crossingAngle || ""}
                      onChange={(e) =>
                        handleFieldChange(
                          "crossingAngle",
                          parseFloat(e.target.value) || 0
                        )
                      }
                      placeholder="交叉角度"
                    />
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="latitude">纬度</Label>
                    <Input
                      id="latitude"
                      type="number"
                      step="0.000001"
                      value={localPoint.latitude || ""}
                      onChange={(e) =>
                        handleFieldChange(
                          "latitude",
                          parseFloat(e.target.value) || 0
                        )
                      }
                      placeholder="纬度坐标"
                    />
                  </div>

                  <div>
                    <Label htmlFor="longitude">经度</Label>
                    <Input
                      id="longitude"
                      type="number"
                      step="0.000001"
                      value={localPoint.longitude || ""}
                      onChange={(e) =>
                        handleFieldChange(
                          "longitude",
                          parseFloat(e.target.value) || 0
                        )
                      }
                      placeholder="经度坐标"
                    />
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="crossingPosition">跨越位置</Label>
                    <Input
                      id="crossingPosition"
                      value={localPoint.crossingPosition || ""}
                      onChange={(e) =>
                        handleFieldChange("crossingPosition", e.target.value)
                      }
                      placeholder="描述具体跨越位置"
                    />
                  </div>

                  <div>
                    <Label htmlFor="crossingPath">跨越路径</Label>
                    <Input
                      id="crossingPath"
                      value={localPoint.crossingPath || ""}
                      onChange={(e) =>
                        handleFieldChange("crossingPath", e.target.value)
                      }
                      placeholder="描述跨越路径"
                    />
                  </div>
                </div>

                <div>
                  <Label htmlFor="protectionRequirements">保护要求</Label>
                  <Textarea
                    id="protectionRequirements"
                    value={localPoint.protectionRequirements || ""}
                    onChange={(e) =>
                      handleFieldChange(
                        "protectionRequirements",
                        e.target.value
                      )
                    }
                    placeholder="详细描述保护要求和注意事项..."
                    rows={3}
                  />
                </div>
              </TabsContent>

              <TabsContent value="gallery" className="space-y-6">
                <ImageGalleryManager />
              </TabsContent>
            </Tabs>

            <div className="flex justify-end gap-3 pt-4 border-t">
              <Button type="button" variant="outline" onClick={onCancel}>
                <X className="w-4 h-4 mr-2" />
                取消
              </Button>
              <Button type="submit" className="bg-blue-600 hover:bg-blue-700">
                <Save className="w-4 h-4 mr-2" />
                保存跨越点
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
